package cn.itcast.web.utils;

import cn.itcast.dao.dept.SysLogDao;
import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import java.util.Date;

@Component
@Aspect
public class SysLogAspect {
@Autowired
    private SysLogService sysLogService;
@Autowired
    private HttpServletRequest request;

   @Around("execution(* cn.itcast.web.controller.*.*.*(..))&&!bean(SysLogController)")
    public Object insertLog(ProceedingJoinPoint pjp){
       try {
           //放行，执行控制器
           Object retV = pjp.proceed();
           //创建日志对象
           SysLog sysLog=new SysLog();
           //设置当前执行的方法名称
           sysLog.setMethod(pjp.getSignature().getName());
           //设置当前执行方法所在的类
           sysLog.setAction(pjp.getTarget().getClass().getName());
           //设置访问者的ip地址
           sysLog.setIp(request.getRemoteAddr());
           //设置访问者的的访问时间
           sysLog.setTime(new Date());

           //通过request获取session对象，再从session中获取登陆用户的key
           User user = (User) request.getSession().getAttribute("loginUser");
           if (user!=null){
               sysLog.setCompanyId(user.getCompanyId());
               sysLog.setCompanyName(user.getCompanyName());
               sysLog.setUserName(user.getUserName());
           }
           //记录日志
           sysLogService.save(sysLog);

           return retV;
       } catch (Throwable throwable) {
           throwable.printStackTrace();
           throw new RuntimeException();
       }
   }


}
